package com.tianji.jd.data.config;

import com.baomidou.dynamic.datasource.ds.AbstractRoutingDataSource;
import com.tianji.jd.data.utile.DynamicDataSourceContextHolder;
import org.springframework.beans.factory.annotation.Autowired;

import javax.sql.DataSource;
import java.util.Map;

/**
 * Description: new java files header..
 *
 * @author chenjia
 * @version 1.0
 * @date 2024/11/12 14:26
 */
public class DynamicRoutingDataSource extends AbstractRoutingDataSource {

    private Map<String, DataSource> dataSourceMap;

    public DynamicRoutingDataSource(Map<String, DataSource> dataSourceMap) {
        this.dataSourceMap = dataSourceMap;
    }


    @Override
    protected DataSource determineDataSource() {
        // 从上下文中获取当前数据源的标识符
        String dataSourceKey = DynamicDataSourceContextHolder.getDataSourceKey();
        // 根据标识符从数据源映射中获取对应的 DataSource
        DataSource dataSource = dataSourceMap.get(dataSourceKey);
        // 如果没有匹配的 DataSource，则使用默认数据源
        return dataSource != null ? dataSource : dataSourceMap.get("default");
    }
}